package com.xiaoxx.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.xiaoxx.config.AliOssConfig;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author :HX
 * @date : 2023/7/11
 */
@Component
public class OssUtil {
    /**
     * 文件一级目录, 文件保存到oss的路径(勿修改 oos/  ), file/ 可修改
     */
    private static final String FILE_PATH = "oss/file/";

    @Resource
    private AliOssConfig aliYunOssProperties;

    public String upload(String filePath, String fileName, InputStream inputStream) {
        // 表示上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String nowDay = format.format(new Date()).concat("/");
        String yourObjectName = FILE_PATH + filePath + nowDay + fileName;
        // 创建ossClient
        OSS ossClient = new OSSClientBuilder().build(aliYunOssProperties.getEndpoint(), aliYunOssProperties.getAccessKeyId(), aliYunOssProperties.getAccessKeySecret());
        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest(aliYunOssProperties.getBucketName(), yourObjectName, inputStream);
        // 上传文件。
        ossClient.putObject(putObjectRequest);
        ossClient.shutdown();
        // 访问地址= 当前服务器域名 + oss存储路径
        return aliYunOssProperties.getBucket() + "/" + yourObjectName;
    }
}
